在前三天的實戰中,我們已經完整搭建了自動化與推論的基礎設施:
從今天開始,我們將正式進入 AI Agent 核心後端服務的開發!為了讓外部通訊端點、商業邏輯計算與 AI 流程之間具備高彈性與高效能,我們選擇現代 Python 開發中最主流的高效能非同步框架——FastAPI 作為我們的核心微服務架構。
今天目標是從零建立 Python 虛擬環境、建置標準專案骨架,並實作第一個具備健康檢查(Health Check)與自動化 Swagger API 文件的後端端點!
在開發 AI Agent 與自動化系統時,後端通常需要頻繁與第三方 API、資料庫及 LLM 進行 I/O 溝通。FastAPI 具備以下核心優勢:
async/await):高併發效能極佳,非常適合等待 LLM 串流回應或外部 Webhook 回調。在 Windows 環境下,建議為專案建立獨立的 Python 虛擬環境(Virtual Environment),以避免套件版本衝突。
請打開 PowerShell,進入昨天的專案目錄或建立專案資料夾:
# 進入專案目錄
cd C:\Users\1124l\food-agent
# 建立專案資料夾
mkdir agent-backend
cd agent-backend
# 建立 Python 虛擬環境(命名為 .venv)
python -m venv .venv
# 啟動虛擬環境
.\.venv\Scripts\Activate.ps1
注意:若執行腳本時遇到權限限制錯誤(ExecutionPolicy),可先在 PowerShell 執行 Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass 後再啟動虛擬環境。終端機前綴出現 (.venv) 即代表啟用成功。
在啟用虛擬環境的狀態下,安裝 FastAPI 以及 ASGI 伺服器 Uvicorn:
pip install fastapi uvicorn[standard] pydantic
為了後續幾天串接資料模型、n8n Webhook 與 LLM Agent,我們規劃清晰模組化的專案骨架:
agent-backend/
├── app/
│ ├── __init__.py
│ ├── main.py # 程式進入點與 FastAPI 實例
│ └── routers/ # API 路由模組
│ ├── __init__.py
│ └── health.py # 健康檢查與系統狀態端點
├── requirements.txt # 套件清單
└── README.md
from fastapi import APIRouter
from pydantic import BaseModel
from datetime import datetime
router = APIRouter(
prefix="/api/v1",
tags=["Health Check"]
)
class HealthResponse(BaseModel):
status: str
service: str
timestamp: str
@router.get("/health", response_model=HealthResponse)
async def check_health():
"""
提供系統心跳檢測(Health Check),用於確認微服務狀態
"""
return HealthResponse(
status="ok",
service="food-agent-backend",
timestamp=datetime.utcnow().isoformat()
)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import health
app = FastAPI(
title="Food Agent Microservice API",
description="智慧餐飲推薦與工作流核心後端服務",
version="1.0.0"
)
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(health.router)
@app.get("/")
async def root():
return {
"message": "Welcome to Food Agent API",
"docs_url": "/docs"
}
pip freeze > requirements.txt
在 agent-backend 目錄下執行 Uvicorn,並啟用 --reload 熱重載模式:
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
當終端機顯示以下資訊即代表伺服器運行中:
INFO: Uvicorn running on [http://0.0.0.0:8000](http://0.0.0.0:8000) (Press CTRL+C to quit)
INFO: Started reloader process [...] using StatReload
INFO: Started server process [...]
INFO: Application startup complete.
打開瀏覽器造訪:http://localhost:8000/docs
畫面會呈現自動生成的 Swagger UI 互動式文件。
點開 GET /api/v1/health 端點,點擊 Try it out ➜ Execute。
確認伺服器回應狀態碼為 200 OK,並回傳格式化 JSON:
"status": "ok",
"service": "food-agent-backend",
"timestamp": "2026-10-05T10:08:47.123456"
}
今日結語與明日預告
今天我們順利建立了 Python FastAPI 的標準微服務專案骨架,完成了第一個健康檢查 API,並驗證了 Swagger 文件的自動生成功能。
目前為止,本地已經具備了三大服務:
FastAPI 核心後端:http://localhost:8000
n8n 自動化流程:http://localhost:5678
Dify AI 應用大腦:http://localhost
明天 Day 05,我們將開始設計餐飲推薦的核心資料結構:使用 Pydantic 定義餐飲資料模型(Schema),並實作第一隻餐點推薦模擬 API,敬請期待!